package logic

import (
	"app-user/common/xerr"
	"app-user/models"
	"context"
	"errors"
	"fmt"
	"time"

	"app-user/protos"
	"app-user/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreateUser 新建用户
func (l *CreateUserLogic) CreateUser(in *protos.NamePassRequest) (*protos.UserInfo, error) {
	_, err := l.svcCtx.UserModel.FindOneByName(l.ctx, in.Name)
	if err != nil && !errors.Is(err, models.ErrNotFound) {
		fmt.Println("CreateUser err:", err.Error())
		return nil, xerr.New(xerr.UserNameError)
	}

	now := time.Now().Unix()
	result, err := l.svcCtx.UserModel.Insert(l.ctx, &models.User{
		Name:       in.Name,
		Password:   in.Password,
		CreateTime: now,
		UpdateTime: now,
	})
	if err != nil {
		return nil, xerr.New(xerr.UserCreateError)
	}
	userID, _ := result.LastInsertId()
	return &protos.UserInfo{Id: userID, Name: in.Name}, nil
}
